import 'package:flutter/material.dart';
import '../utils/app_theme.dart';

class CommunityScreen extends StatefulWidget {
  const CommunityScreen({super.key});

  @override
  State<CommunityScreen> createState() => _CommunityScreenState();
}

class _CommunityScreenState extends State<CommunityScreen> with SingleTickerProviderStateMixin {
  late TabController _tabController;
  final TextEditingController _postController = TextEditingController();
  
  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 2, vsync: this);
  }
  
  @override
  void dispose() {
    _tabController.dispose();
    _postController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('习惯社区'),
        bottom: TabBar(
          controller: _tabController,
          tabs: const [
            Tab(text: '热门讨论'),
            Tab(text: '我的关注'),
          ],
        ),
      ),
      body: TabBarView(
        controller: _tabController,
        children: [
          // Hot topics tab
          _buildHotTopicsTab(),
          
          // My following tab
          _buildFollowingTab(),
        ],
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _showNewPostDialog,
        backgroundColor: AppTheme.primaryColor,
        child: const Icon(Icons.add),
      ),
    );
  }
  
  Widget _buildHotTopicsTab() {
    return ListView(
      padding: const EdgeInsets.all(16),
      children: [
        _buildPromotionCard(),
        const SizedBox(height: 16),
        ...List.generate(5, (index) => _buildPostCard(index)),
      ],
    );
  }
  
  Widget _buildFollowingTab() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          const Icon(
            Icons.people_outline,
            size: 80,
            color: Colors.grey,
          ),
          const SizedBox(height: 16),
          const Text(
            '您尚未关注任何人',
            style: AppTheme.subheadingStyle,
          ),
          const SizedBox(height: 8),
          const Text(
            '关注其他用户以查看他们的习惯和进度分享',
            style: TextStyle(color: AppTheme.textSecondaryColor),
            textAlign: TextAlign.center,
          ),
          const SizedBox(height: 24),
          ElevatedButton.icon(
            onPressed: () {
              _tabController.animateTo(0);
            },
            icon: const Icon(Icons.explore),
            label: const Text('探索社区'),
            style: AppTheme.primaryButtonStyle,
          ),
        ],
      ),
    );
  }
  
  Widget _buildPromotionCard() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(12),
        gradient: const LinearGradient(
          colors: [Color(0xFF4A6572), Color(0xFF61A4F1)],
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
        ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            '加入习惯挑战',
            style: TextStyle(
              color: Colors.white,
              fontSize: 20,
              fontWeight: FontWeight.bold,
            ),
          ),
          const SizedBox(height: 8),
          const Text(
            '与其他用户一起参与 "21天早起挑战"',
            style: TextStyle(
              color: Colors.white,
              fontSize: 16,
            ),
          ),
          const SizedBox(height: 16),
          Row(
            children: [
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(20),
                ),
                child: const Text(
                  '已有 128 人参与',
                  style: TextStyle(
                    color: Color(0xFF4A6572),
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
              const Spacer(),
              ElevatedButton(
                onPressed: () {
                  ScaffoldMessenger.of(context).showSnackBar(
                    const SnackBar(
                      content: Text('挑战功能正在开发中'),
                      behavior: SnackBarBehavior.floating,
                    ),
                  );
                },
                style: ElevatedButton.styleFrom(
                  backgroundColor: Colors.white,
                  foregroundColor: const Color(0xFF4A6572),
                ),
                child: const Text('参与挑战'),
              ),
            ],
          ),
        ],
      ),
    );
  }
  
  Widget _buildPostCard(int index) {
    // Sample post data
    final List<Map<String, dynamic>> posts = [
      {
        'username': '晨曦',
        'avatar': 'https://randomuser.me/api/portraits/women/32.jpg',
        'habit': '晨间冥想',
        'content': '连续冥想30天了，感觉专注力有了很大提升，也更容易控制情绪了。大家有什么冥想的小技巧可以分享吗？',
        'likes': 24,
        'comments': 8,
        'time': '2小时前',
      },
      {
        'username': '健身达人',
        'avatar': 'https://randomuser.me/api/portraits/men/45.jpg',
        'habit': '每日运动',
        'content': '分享一个适合在家进行的10分钟高强度训练，不需要任何器材：30秒开合跳 → 30秒平板支撑 → 30秒深蹲 → 30秒俯卧撑，重复2-3组。',
        'likes': 45,
        'comments': 12,
        'time': '3小时前',
      },
      {
        'username': '读书人',
        'avatar': 'https://randomuser.me/api/portraits/women/65.jpg',
        'habit': '每日阅读',
        'content': '推荐一本书《原子习惯》，作者详细讲解了如何通过微小的改变实现巨大的成果。我已经按照书中的方法坚持了两个月，效果很明显。',
        'likes': 67,
        'comments': 15,
        'time': '昨天',
      },
      {
        'username': '早起鸟',
        'avatar': 'https://randomuser.me/api/portraits/men/22.jpg',
        'habit': '早起',
        'content': '坚持早起一个月，终于不再赖床了！分享我的方法：把闹钟放在离床远的地方，被迫起床关闹钟；起床后立即喝一杯水，然后做3分钟拉伸运动。',
        'likes': 38,
        'comments': 7,
        'time': '昨天',
      },
      {
        'username': '水滴',
        'avatar': 'https://randomuser.me/api/portraits/women/8.jpg',
        'habit': '喝水',
        'content': '我发现使用提醒类App真的很有用，现在已经能自然地养成每天喝2000ml水的习惯。大家有什么实用的提醒工具推荐吗？',
        'likes': 19,
        'comments': 11,
        'time': '2天前',
      },
    ];
    
    final post = index < posts.length ? posts[index] : posts[0];
    
    return Container(
      margin: const EdgeInsets.only(bottom: 16),
      decoration: AppTheme.cardDecoration,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // Post header
          ListTile(
            leading: CircleAvatar(
              backgroundImage: NetworkImage(post['avatar']),
            ),
            title: Text(
              post['username'],
              style: const TextStyle(fontWeight: FontWeight.bold),
            ),
            subtitle: Text('习惯：${post['habit']}'),
            trailing: Text(
              post['time'],
              style: const TextStyle(color: AppTheme.textSecondaryColor),
            ),
          ),
          
          // Post content
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
            child: Text(
              post['content'],
              style: AppTheme.bodyStyle,
            ),
          ),
          
          // Post actions
          Padding(
            padding: const EdgeInsets.all(8),
            child: Row(
              children: [
                IconButton(
                  icon: const Icon(Icons.favorite_border),
                  onPressed: () {
                    ScaffoldMessenger.of(context).showSnackBar(
                      const SnackBar(
                        content: Text('点赞功能正在开发中'),
                        behavior: SnackBarBehavior.floating,
                      ),
                    );
                  },
                ),
                Text('${post['likes']}'),
                const SizedBox(width: 16),
                IconButton(
                  icon: const Icon(Icons.comment_outlined),
                  onPressed: () {
                    ScaffoldMessenger.of(context).showSnackBar(
                      const SnackBar(
                        content: Text('评论功能正在开发中'),
                        behavior: SnackBarBehavior.floating,
                      ),
                    );
                  },
                ),
                Text('${post['comments']}'),
                const Spacer(),
                IconButton(
                  icon: const Icon(Icons.share_outlined),
                  onPressed: () {
                    ScaffoldMessenger.of(context).showSnackBar(
                      const SnackBar(
                        content: Text('分享功能正在开发中'),
                        behavior: SnackBarBehavior.floating,
                      ),
                    );
                  },
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
  
  void _showNewPostDialog() {
    showDialog(
      context: context,
      builder: (ctx) => AlertDialog(
        title: const Text('分享您的习惯体验'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            TextField(
              controller: _postController,
              maxLines: 5,
              decoration: const InputDecoration(
                hintText: '分享您的习惯心得、进步或寻求建议...',
                border: OutlineInputBorder(),
              ),
            ),
            const SizedBox(height: 16),
            Row(
              children: [
                IconButton(
                  icon: const Icon(Icons.photo),
                  onPressed: () {
                    ScaffoldMessenger.of(context).showSnackBar(
                      const SnackBar(
                        content: Text('添加图片功能正在开发中'),
                        behavior: SnackBarBehavior.floating,
                      ),
                    );
                  },
                ),
                IconButton(
                  icon: const Icon(Icons.tag),
                  onPressed: () {
                    ScaffoldMessenger.of(context).showSnackBar(
                      const SnackBar(
                        content: Text('添加标签功能正在开发中'),
                        behavior: SnackBarBehavior.floating,
                      ),
                    );
                  },
                ),
              ],
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () {
              if (_postController.text.isNotEmpty) {
                Navigator.of(context).pop();
                _postController.clear();
                
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(
                    content: Text('您的分享已发布'),
                    behavior: SnackBarBehavior.floating,
                  ),
                );
              }
            },
            child: const Text('发布'),
          ),
        ],
      ),
    );
  }
}
